import Vue from 'vue'
import Vuex from 'vuex'
import $cache from '@/common/cache.js';
import {
	getUserInfo,
	getStatus
} from '@/apis/index.js'
import indexConfig from '@/config/index.config.js'
const TOKEN = $cache.getStorageSync("token");
const USER_INFO = $cache.getStorageSync("userInfo");
const IS_PROD = $cache.getStorageSync("isprod");
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		// 前端token
		token: TOKEN,
		// 用户信息 头像 昵称
		userInfo: USER_INFO,
		isprod: IS_PROD, //生产环境
	},
	getters: {
		// 用户是否登录
		hasLogin: state => {
			let _token = state.token;
			if (_token == undefined) {
				_token = $cache.getStorageSync("token");
			}
			if (_token) {
				return true;
			} else {
				return false
			}
		},
		// 用户是否有手机号
		hasMobile: state => {
			let _mobile = state.userInfo.mobile;
			if (_mobile) {
				return true;
			} else {
				return false
			}
		},
	},
	mutations: {
		SET_TOKEN(state, token) {
			state.token = token;
			$cache.setStorageSync("token", token);
		},
		SET_OPENID(state, openid) {
			$cache.setStorageSync("openid", openid);
		},
		SET_USERINFO(state, userInfo) {
			state.userInfo = userInfo;
			$cache.setStorageSync("userInfo", userInfo);
		},
		SET_IS_PROD(state, status) {
			state.isprod = status;
			$cache.setStorageSync("isprod", status);
		},
		SET_LOGOUT(state) {
			state.token = "";
			state.userInfo = "";
			$cache.removeStorageSync("userInfo");
			$cache.removeStorageSync("token");
		},
	},
	actions: {
		//更新用户信息
		UPDATA_USER_INFO({
			commit
		}) {
			getUserInfo().then(result => {
				let res = result;
				if (res.code == 200) {
					commit('SET_USERINFO', res.data)
				}
			}).catch(err => {});
		},
		//获取状态
		GET_STATUS({
			commit
		}) {
			getStatus({
				version: indexConfig.versionName
			}).then(result => {
				let res = result;
				if (res.code == 200) {
					commit('SET_IS_PROD', res.data)
				}
			}).catch(err => {});
		}
	}
})
export default store